package cs2340.droidceptiontodo.test;
import cs2340.droidceptiontodo.Database;
import cs2340.droidceptiontodo.LoginActivity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import android.widget.EditText;

/**
 * 
 * @author Susmita Gorai
 * LoginActivityValidation class to test loginActivity 
 */
public class LoginActivityValidation extends ActivityInstrumentationTestCase2<LoginActivity> {
	private LoginActivity activity;
	EditText logName, passName;
	Button loginButton;
	private Database db;
	
	public LoginActivityValidation() {
		super("cs2340.droidceptiontodo", LoginActivity.class);
	}

	/**
	 * Setup method for initialization and preparation before testing
	 */
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		activity = getActivity();
		logName = (EditText)activity.findViewById(cs2340.droidceptiontodo.R.id.editText1);
		passName = (EditText)activity.findViewById(cs2340.droidceptiontodo.R.id.editText2);
		loginButton = (Button)activity.findViewById(cs2340.droidceptiontodo.R.id.button1);
        db = new Database(activity.getApplicationContext());
        db.open();
	}
    
	/**
	 * test method for onCreate() method of LoginActivity class
	 * A separate thread required to input values to editText fields
	 */
	
	public final void testOnCreate()
	{
		boolean found= false;
		activity.runOnUiThread(new Runnable(){
			@Override
			public void run(){
				logName.setText("bat");
				passName.setText("bat12");
				loginButton.performClick();
			}
		});
		getInstrumentation().waitForIdleSync(); 
		String log = logName.getText().toString();
        String pass = passName.getText().toString();
        if((log.equals("bat")) && (pass.equals("bat12")))
        	found = true;
        assertTrue("login verified", found == true);
    }
	
 
	
	
	/**
	 * Check onClick() method by verifying login/password from database
	 */
	public final void testOnClick() {
		boolean loginValid = false;
		activity.runOnUiThread(new Runnable(){
			@Override
			public void run(){
				logName.setText("bat");
				passName.setText("bat12");
			}
		});
		//retrieves username and password from fields and assigns them to variables
		String lgn = logName.getText().toString();
		String password = passName.getText().toString();
		//creates a database object, which in reality just pulls up the old database
		try{
			 //stores the int result of the log in checker
			int res = db.checkUser(lgn, password);
			if (res == 1)
				loginValid = true;
		}
		catch(Exception e){
		}
		assertTrue("Login valid", loginValid == true);
	}
	
	/**
	 * Closes the database
	 */
	@Override
	protected void tearDown() throws Exception {
		db.close();
	    super.tearDown();
	}
}
